package chat.controller;


import chat.UserDto.LogChatDto;

import chat.service.LogChatService;
import chat.utils.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.revery.api.api.chat.IChatApi;
import top.revery.api.config.UserPageData;
import top.revery.api.entity.chat.BaseLogChat;
import top.revery.api.util.ImConfig;
import chat.utils.Message;
import chat.utils.MsgBody;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Timestamp;
import java.util.*;

/**
 * @author denghao
 * @title
 * @package
 * @date 2019/12/31 15:11
 */
@Slf4j
@RestController
public class UserController implements IChatApi{
    @Autowired
    private LogChatDto logChatDto;
    @Autowired
    private LogChatService logChatService;


    //单个账户导入
    @Override
    public JSONObject amount(String identifier) {
        String sign = TencentIMHelper.getUsig("administrator");
        Map<String, Object> map = new HashMap();
        map.put("usersig", sign);
        map.put("identifier", "administrator");
        map.put("sdkappid", ImConfig.TENCENT_SDKAPPID);
        map.put("contenttype", "json");

        String s = TencentIMHelper.createString(map);
        String url = ImConfig.account_import_address + s;
        System.out.println(s);
        JSONObject obj = reveryTool.http(url, "{\"Identifier\":" + "\"" + identifier + "\"}");
        System.out.println(obj);
        System.out.println(obj.containsValue("OK"));
        if (!obj.containsValue("OK")) {
            log.error("导入'{}'到腾讯云IM失败, response message is: {}", obj);
        }
        return obj;
    }

    //系统向用户向用户发送消息
    @Override
    public JSONObject smsMessageSys(String fromUser, String toUser, String msgBody1) {
        MsgBody msgBody = (MsgBody)JSONObject.parse(msgBody1);
        String MsgType = msgBody.getMsgType();
        // MsgContent MsgContent =msgBody.getMsgContent();
        String sign = TencentIMHelper.getUsig("administrator");
        Map<String, Object> map = new HashMap();
        map.put("usersig", sign);
        map.put("identifier", "administrator");
        map.put("sdkappid", ImConfig.TENCENT_SDKAPPID);
        map.put("contenttype", "json");

        /*  MsgBody msgBody = message.getMsgBody().get(0);*/
        JSONArray jsonArray = new JSONArray();
        JSONObject body = new JSONObject();
        if (MsgType.equals("TIMTextElem")) {
            body.put("MsgType", "TIMTextElem");
            body.put("MsgContent", JSON.parseObject("{\"Text\": \"" + msgBody.getMsgContent().getText() + "\"}"));
            jsonArray.add(body);
        }
        if (msgBody.getMsgType().equals("TIMLocationElem")) {
            body.put("MsgType", "TIMLocationElem");
            body.put("MsgContent", JSON.parseObject("{\"Desc\": \"" + msgBody.getMsgContent().getDesc() +
                    "\",\"Latitude\":" + msgBody.getMsgContent().getLatitude() +
                    ",\"Longitude\":" + msgBody.getMsgContent().getLongitude() +
                    "}"));
            jsonArray.add(body);
        }
        if (msgBody.getMsgType().equals("TIMFaceElem")) {
            body.put("MsgType", "TIMFaceElem");
            body.put("MsgContent", JSON.parseObject("{\"Index\":" + msgBody.getMsgContent().getIndex() +
                    ",\"Data\":\"" + msgBody.getMsgContent().getData() +
                    "\"}"));
            jsonArray.add(body);
        }
        if (msgBody.getMsgType().equals("TIMCustomElem")) {
            body.put("MsgType", "TIMCustomElem");
            body.put("MsgContent", JSON.parseObject("{\"Data\": \"" + msgBody.getMsgContent().getData() + "\"" +
                    ",\"Desc\":\"" + msgBody.getMsgContent().getDesc() + "\"" +
                    "}"));
            jsonArray.add(body);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("SyncOtherMachine", 1);
        jsonObject.put("From_Account", fromUser);
        jsonObject.put("To_Account", toUser);
        jsonObject.put("MsgRandom", reveryTool.getRomdom());
        //jsonObject.put("MsgLifeTime", 3600);
        jsonObject.put("MsgTimeStamp", Integer.valueOf((int) System.currentTimeMillis()));
        jsonObject.put("MsgBody", jsonArray);

        String s = TencentIMHelper.createString(map);
        String url = ImConfig.send_msg_address + s;
        System.out.println(s);
        System.out.println(url);
        JSONObject obj = reveryTool.http(url, jsonObject.toJSONString());
        System.out.println(obj);
        System.out.println(obj.containsValue("OK"));
        if (!obj.containsValue("OK")) {
            log.error("导入'{}'到腾讯云IM失败, response message is: {}", obj);
        }
        return obj;
    }

    @Override
    public JSONObject smsMessageAll(String message1) {
        Message message = (Message) JSONObject.parse(message1);
        String to_Account = message.getToAccount();
        List<String> list = new ArrayList<>();
        String[] split = to_Account.split(",");
        for (String s : split) {
            list.add(s);
        }
        //   System.out.println(list);
        String sign = TencentIMHelper.getUsig("administrator");
        Map<String, Object> map = new HashMap();
        map.put("usersig", sign);
        map.put("identifier", "administrator");
        map.put("sdkappid", ImConfig.TENCENT_SDKAPPID);
        map.put("contenttype", "json");
        MsgBody msgBody = message.getMsgBody().get(0);
        JSONArray jsonArray = new JSONArray();
        JSONObject body = new JSONObject();

        if (msgBody.getMsgType().equals("TIMTextElem")) {
            body.put("MsgType", "TIMTextElem");
            body.put("MsgContent", JSON.parseObject("{\"Text\": \"" + msgBody.getMsgContent().getText() + "\"}"));
            jsonArray.add(body);
        }
        if (msgBody.getMsgType().equals("TIMLocationElem")) {
            body.put("MsgType", "TIMLocationElem");
            body.put("MsgContent", JSON.parseObject("{\"Desc\": \"" + msgBody.getMsgContent().getDesc() +
                    "\",\"Latitude\":" + msgBody.getMsgContent().getLatitude() +
                    ",\"Longitude\":" + msgBody.getMsgContent().getLongitude() +
                    "}"));
            jsonArray.add(body);
        }
        if (msgBody.getMsgType().equals("TIMFaceElem")) {
            body.put("MsgType", "TIMFaceElem");
            body.put("MsgContent", JSON.parseObject("{\"Index\":" + msgBody.getMsgContent().getIndex() +
                    ",\"Data\":\"" + msgBody.getMsgContent().getData() +
                    "\"}"));
            jsonArray.add(body);
        }
        if (msgBody.getMsgType().equals("TIMCustomElem")) {
            body.put("MsgType", "TIMCustomElem");
            body.put("MsgContent", JSON.parseObject("{\"Data\": \"" + msgBody.getMsgContent().getData() + "\"" +
                    ",\"Desc\":\"" + msgBody.getMsgContent().getDesc() + "\"" +
                    "}"));
            jsonArray.add(body);
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("SyncOtherMachine", message.getSyncOtherMachine());
        jsonObject.put("To_Account", list);
        jsonObject.put("MsgLifeTime", message.getMsgLifeTime());
        jsonObject.put("MsgRandom", message.getMsgRandom());
        // jsonObject.put("MsgTimeStamp", message.getMsgTimeStamp());
        jsonObject.put("MsgBody", jsonArray);

        String s = TencentIMHelper.createString(map);
        String url = ImConfig.send_msg_all + s;
        System.out.println(s);
        JSONObject obj = reveryTool.http(url, jsonObject.toJSONString());
        System.out.println(obj);
        System.out.println(obj.containsValue("OK"));

        if (!obj.containsValue("OK")) {
            log.error("导入'{}'到腾讯云IM失败, response message is: {}", obj);
        }

        for (String s1 : list) {
            BaseLogChat baseLogChat = new BaseLogChat();
            baseLogChat.setMsgBody(body.toJSONString());
            baseLogChat.setToAccount(s1);
            baseLogChat.setFromAccount("0");
            baseLogChat.setAddTime(new Timestamp(new Date().getTime()));
            logChatDto.save(baseLogChat);
        }

        return obj;
    }
    @Override
    public JSONObject notify(HttpServletRequest request) throws IOException {
        try {
            Map<String, String[]> parameterMap = request.getParameterMap();
            Map<String, String> paramsMap = new HashMap<>();

            parameterMap.forEach((key, values) -> {
                String strs = "";
                for (String value : values) {
                    strs = strs + value;
                }
                System.out.println(("key值为" + key + "value为：" + strs));
                paramsMap.put(key, strs);
            });
            System.out.println(paramsMap);
            InputStream inputStream;
            inputStream = request.getInputStream();
            StringBuffer sb = new StringBuffer();
            String s;
            BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            while ((s = in.readLine()) != null) {
                sb.append(s);
            }
            in.close();
            inputStream.close();
            System.out.println("sb:" + sb.toString());
            String s1 = sb.toString();
            JSONObject jb = JSONObject.parseObject(s1);
            String from_account = jb.getString("From_Account");
            String to_account = jb.getString("To_Account");
            String msgBody = jb.getString("MsgBody");
            BaseLogChat baseLogChat = new BaseLogChat();
            baseLogChat.setMsgBody(msgBody);
            baseLogChat.setToAccount(to_account);
            baseLogChat.setFromAccount(from_account);
            baseLogChat.setAddTime(new Timestamp(new Date().getTime()));
            logChatDto.save(baseLogChat);
            JSONObject obj = new JSONObject();
            obj.put("ActionStatus", "OK");
            obj.put("ErrorCode", 0);
            if (!obj.containsValue("OK")) {
                log.error("调用失败, response message is: {}", obj);
            }
            return obj;

        } catch (Exception e) {

            e.printStackTrace();
            log.error("调用失败，系统异常");
            return null;
        }

    }


    @Override
    public List<BaseLogChat> getUserList(String toAccount) {
        List<BaseLogChat> logChatList = logChatDto.findByToAccount(toAccount);
        HashSet<String> setList = new HashSet<>();
        for (BaseLogChat baseLogChat : logChatList) {
            String from_account = baseLogChat.getFromAccount();
            baseLogChat.getAddTime();
            setList.add(from_account);
        }
        List<BaseLogChat> logChatList1 = new ArrayList<>();
        for (String s:setList){
            List<BaseLogChat> baseLogChats =logChatDto.findByToAccountAndFromAccount(toAccount,s);
            BaseLogChat baseLogChat = baseLogChats.get(baseLogChats.size() - 1);
            logChatList1.add(baseLogChat);
        }

        Collections.sort(logChatList1, new Comparator<BaseLogChat>(){
            public int compare(BaseLogChat o1, BaseLogChat o2) {
                //按照时间大小进行降序排列
                if(o1.getAddTime().getTime() < o2.getAddTime().getTime()){
                    return 1;
                }
                if(o1.getAddTime().getTime() == o2.getAddTime().getTime()){
                    return 0;
                }
                return -1;
            }
        });
        System.out.println(logChatList1);
        return logChatList1;

    }

    @Override
    public UserPageData getList(int pageNum, int pageSize, Map map) {
        Page<BaseLogChat> pageList = logChatService.getList(pageNum, pageSize, map);
        UserPageData pageData = new UserPageData();
        pageData.list = pageList.getContent();
        pageData.rows = pageList.getTotalElements();
        return pageData;

    }


}
